using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.Logic;
using NetProtocol.Client;
using NetProtocol.POD;

namespace IQIGame.Onigao.GamePlay
{
    public class LevelModule : Singleton<LevelModule>, CNetLevel
    {
        private LevelModule() { }
        public static CNetLevel NetCore => Instance;

        void CNetLevel.SC_localNotifyCreateLevel(ISession session, LogicPlayerPOD playerPOD, CreateLevelPOD createLevelPOD)
        {
            CreateLocalLevel(playerPOD, createLevelPOD).Forget();
        }

        private async UniTaskVoid CreateLocalLevel(LogicPlayerPOD playerPOD, CreateLevelPOD createLevelPOD)
        {
            await GameplayAreaManager.Instance.SwitchAwait(GameplayAreaType.Level, (createLevelPOD.cid, true));
            LogicHelper.Router = new ClientProtocolRouter();
            LogicHelper.OnPlayerEnterLevel = (pid, levelId) => NetCore.CS_localNotifyEnterLevel(levelId);
            LogicHelper.SaveLevel = (_, levelId, savePOD) =>
            {
                RequestSaveLevelPOD requestSaveLevelPOD = new RequestSaveLevelPOD();
                requestSaveLevelPOD.levelCid = savePOD.cid;
                requestSaveLevelPOD.levelId = levelId;
                requestSaveLevelPOD.saveData = savePOD;
                NetCore.CS_localRequestSave(requestSaveLevelPOD);
            };
            LogicHelper.OnPlayerLeaveLevel = (pid, levelId) => NetCore.CS_localNotifyExitLevel(levelId);
            CLevelLogicModule.Instance.InitLocalLevel(createLevelPOD, (LevelSavePOD)createLevelPOD.saveData, playerPOD);
        }

        void CNetLevel.SC_localS2CNotifyDataSyncEvent(ISession session, DataSyncEventPOD eventPOD)
        {
            LogicDataSyncModule.Instance.OnSyncDataEvent(eventPOD);
        }

        void CNetLevel.SC_localNotifyShutdownLevel(ISession session, long levelId)
        {
            CLevelLogicModule.Instance.ShutdownLocalLevel();
        }

        ISession CNetLevel.GetSession()
        {
            return GameServerModule.Instance.CurrSession;
        }
    }
}